package com.wujilee.wujileenetty.demos.web.nio;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.sql.Array;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author liwuji
 * @date 2024/7/30
 * @desc
 **/

@Slf4j
public class NioServer {
    public static void main(String[] args) throws IOException {

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(6666));
        serverSocketChannel.configureBlocking(false);
        Selector selector = Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        while (true) {
            if (selector.select(1000) == 0) {
                continue;
            }

            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                try {
                    SelectionKey selectionKey = iterator.next();
                    if (selectionKey.isAcceptable()) {
                        try {
                            SocketChannel socketChannel = serverSocketChannel.accept();
                            System.out.println("服务端接收到了accept新的连接");
                            socketChannel.configureBlocking(false);
                            socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }

                    if (selectionKey.isReadable()) {
                        System.out.println("服务端接收到了新read的消息");
                        SocketChannel channel = (SocketChannel) selectionKey.channel();
                        ByteBuffer attachment = (ByteBuffer) selectionKey.attachment();
                        try {
                            int read = channel.read(attachment);
                            if (read == -1) {
                                // 客户端断开
                                System.out.println("连接断开");
                                selectionKey.cancel();
                            } else {
                                if(read == 0){
                                    System.out.println("接收完毕");
                                }
                                attachment.flip();
                                byte[] data = new byte[attachment.limit()];
                                attachment.get(data);
                                System.out.println("服务端接收到数据: " + new String(data));
                                attachment.clear();
                            }
                        } catch (IOException e) {
                            // 服务端异常断开
                            selectionKey.cancel();
                            throw new RuntimeException(e);
                        }
                    }
                    iterator.remove();
                } catch (Exception e) {
                    log.error("服务端处理消息异常", e);
                }
            }
        }

    }
}
